package com.example.grpc.openapi.client;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

public class GrpcClient {

    /**
     * 通道地址
     */
    protected final String target;

    /**
     * 超时时间
     */
    protected final long timeout;

    /**
     * 默认超时时间单位（毫秒）
     */
    protected static final TimeUnit DEFAULT_TIMEOUT_UNIT = TimeUnit.MILLISECONDS;

    public GrpcClient(String target, long timeout) {
        if (StringUtils.isEmpty(target)) {
            throw new IllegalArgumentException("Metadata grpc server target could not be blank.");
        }

        if (timeout <= 0) {
            throw new IllegalArgumentException("Metadata grpc client timeout should greater than 0.");
        }
        this.target = target;
        this.timeout = timeout;
    }

    protected ManagedChannel getChannel() {
        return ManagedChannelBuilder.forTarget(target)
                .usePlaintext()
                .build();
    }

    protected long getTimeout() {
        return timeout;
    }

    protected void shutdownChannel(ManagedChannel channel) {
        if (channel != null && !channel.isShutdown()) {
            channel.shutdown();
        }
    }

}
